﻿using AutoMapper;
using MediatR;
using Traceable.App.Application.Command.Processing;
using Traceable.Domian;
using Traceable.ErrorCode;
using Traceable.Infastructure;

namespace Traceable.App.Application.Handler.Processing
{
    public class CreateSuppliersHandler : IRequestHandler<CreateSuppliersCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Suppliers_Table> _suppliersRepo;
        private readonly IMapper _mapper;

        public CreateSuppliersHandler(IBaseRepository<Suppliers_Table> suppliersRepo, IMapper mapper)
        {
            _suppliersRepo = suppliersRepo;
            _mapper = mapper;
        }
        /// <summary>
        /// 添加供应商管理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateSuppliersCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var suppliers = _suppliersRepo.GetAll().Where(p => p.Batch_Id == request.Batch_Id && p.Suppliers_Type == request.Suppliers_Type).FirstOrDefault();
             if (suppliers == null)
            {
                var model = _mapper.Map<Suppliers_Table>(request);
                model.CreateTime= DateTime.Now;
                model.Creater = "张三";
                model.UpdateTime= DateTime.Now;
                var res =_suppliersRepo.Add(model);
                if(res>0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "保存成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.Fail;
                    result.Data = res;
                    result.Message = "保存失败";
                    return Task.FromResult(result);
                }
            }
            else
            {
                suppliers = _mapper.Map(request, suppliers);
                suppliers.UpdateTime = DateTime.Now;
                suppliers.Updater = "张三";
                var res = _suppliersRepo.Update(suppliers);
                if (res > 0)
                {
                    result.Code = StatusEnum.OK;
                    result.Data = res;
                    result.Message = "保存成功";
                    return Task.FromResult(result);
                }
                else
                {
                    result.Code = StatusEnum.Fail;
                    result.Data = res;
                    result.Message = "保存失败";
                    return Task.FromResult(result);
                }
            }
        }
    }
}
